import { App } from "../App";
import { Singleton } from "./Class";


/**
 * 头像管理操作
 *
 * @class _AvatarManager
 * @extends {BaseClass}
 */
export default class AvatarMgr extends Singleton<AvatarMgr> {
    private _headCache = {};
    constructor() {
        super();
    }

    protected onInit(list:number[]|string[]){
        App.Res.loadRes(`head/head:hall`,cc.SpriteAtlas,(atlas:cc.SpriteAtlas)=>{
            list && list.forEach((idx)=>{
                this._headCache[`${idx}`] = atlas.getSpriteFrame(idx);
            });
        });
    }
    
    public setHead(url: string | number, node: cc.Sprite|cc.Node) {
        if (!node || App.Util.isInvalid(url)) return ;

        let _sprite = node.getComponent(cc.Sprite);
        !_sprite && (_sprite = node.addComponent(cc.Sprite));

        url = url.toString().replace(/(^\s*)|(\s*$)/g, '');
        if (App.Util.isEmpty(url)){
            _sprite.spriteFrame = null;
            return ;
        }
        const cache = this._headCache[url];
        if (cache){
            _sprite.spriteFrame = cache;
            return ;
        }

        if (url.indexOf('http://') === 0 || url.indexOf('https://') === 0){
            App.Res.loadRemote(url,(res:cc.Texture2D)=>{
                let _sf = new cc.SpriteFrame(res);
                _sf && (_sprite.spriteFrame = _sf);
                this._headCache[url] = _sf;
            });
        }
    };

    public getAllLocal() {
        return this._headCache;
    }
}